import { defineStore } from "pinia";
import { UserState } from "~/store/modulers/user/types";
import { createAxios } from "~/api/util/request-wrapper";
import router from "~/router";
import { useMenuStore } from "~/store/modulers/menu";

export const useUserStore = defineStore("icesoft-user", {
  persist: {
    enabled: true,
  },
  state() {
    const state: UserState = { token: undefined, user: {}, username: "" };
    return state;
  },

  actions: {
    setUserInfo(data: UserState) {
      window.localStorage.setItem("token", <string>data.token);
      this.token = data.token;
      this.username = data.username;
      this.user = data as any;
    },
    logout() {
      const http = createAxios();
      http.post("/auth/logout").then(res => {
        if (res.ok) {
          this.$reset();
          useMenuStore().$reset();
          window.localStorage.removeItem("token");
          router.push("/login");
        }
      });
    },
    setCompany(e: any) {
      this.user.company = e;
    },
  },
});
